package yuan.deng.mapper;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import yuan.deng.pojo.User;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class Demo1 {
    private InputStream is;
    private SqlSession sqlSession ;
    @Before
    public void before() throws IOException {
        //读取mybatis核心配置文件
         is = Resources.getResourceAsStream("Config.xml");
        //构建工厂对象
        SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(is);
        //获取sqlsession对象
        sqlSession = sqlSessionFactory.openSession();

    }
    @After
    public void after(){
        sqlSession.commit();
        sqlSession.close();
    }
    @Test
    public void findAll(){
        List<User> users = sqlSession.selectList("user.findAll");
        for (int i = 0; i < users.size(); i++) {
            System.out.println(users.get(i));
        }
    }
    @Test
    public void findById(){
        User u = sqlSession.selectOne("user.findById",2);
        System.out.println(u);
    }
    @Test
    public void findCount(){
        Map<Integer,Object> map=new HashMap<>();
        List<Map<Integer,Object>> list = sqlSession.selectList("user.count");
        for(Map<Integer,Object> map1 :list){
            Integer age = (Integer)map1.get("age");
            Object total= map1.get("total");
            map.put(age,total);
        };
        System.out.println(map);
    }
    @Test
    public void findUser(){
        User user=new User();
        user.setId(2);
        User u = sqlSession.selectOne("user.findUser",user);
        System.out.println(u);
    }
    @Test
    public void findLike(){
        User user=new User();
        user.setName("%五%");
        User u = sqlSession.selectOne("user.findLike",user);
        System.out.println(u);
    }
}
